package com.crm.api.service.impl;

import com.crm.api.entity.Employee;
import com.crm.api.mapper.EmployeeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户详情服务实现类
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询员工信息
        Employee employee = employeeMapper.findByUsername(username);

        if (employee == null) {
            log.error("用户不存在: {}", username);
            throw new UsernameNotFoundException("用户不存在");
        }

        // 如果员工不在职，禁止登录
        if (!employee.getIsActive()) {
            log.error("用户已禁用: {}", username);
            throw new UsernameNotFoundException("用户已禁用");
        }

        // 设置权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_" + employee.getRole().toUpperCase()));

        // 返回UserDetails
        return new User(
                employee.getUsername(),
                employee.getPassword(),
                authorities);
    }
}